import React, { useState, useEffect } from 'react';
import { Row, Col, Card, Statistic, Button, Carousel, List, Avatar, Tag } from 'antd';
import {
  BookOutlined,
  UserOutlined,
  VideoCameraOutlined,
  StarOutlined,
  PlayCircleOutlined,
  EyeOutlined,
  ClockCircleOutlined,
} from '@ant-design/icons';
import { useNavigate } from 'react-router-dom';
import { courseAPI } from '../../utils/api';
import useAuthStore from '../../stores/authStore';
import './index.scss';

const Home = () => {
  const navigate = useNavigate();
  const { user } = useAuthStore();
  const [stats, setStats] = useState({
    totalCourses: 0,
    totalStudents: 0,
    totalTeachers: 0,
    totalLives: 0,
  });
  const [featuredCourses, setFeaturedCourses] = useState([]);
  const [liveStreams, setLiveStreams] = useState([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    fetchHomeData();
  }, []);

  const fetchHomeData = async () => {
    try {
      setLoading(true);
      
      // 获取统计数据
      const statsResponse = await Promise.all([
        courseAPI.getCourses({ limit: 1 }),
      ]);

      // 获取推荐课程
      const coursesResponse = await courseAPI.getCourses({
        featured: true,
        limit: 6,
      });

      // 获取直播列表
      const livesResponse = []

      setStats({
        totalCourses: coursesResponse.total || 0,
        totalStudents: 1250,
        totalTeachers: 45,
        totalLives: livesResponse.total || 0,
      });
      console.log(coursesResponse);
      setFeaturedCourses(coursesResponse.data.list || []);
      setLiveStreams(livesResponse.data || []);
    } catch (error) {
      console.error('Failed to fetch home data:', error);
    } finally {
      setLoading(false);
    }
  };

  const bannerItems = [
    {
      title: '精品课程',
      description: '海量优质课程，助你快速提升技能',
      image: '/images/banner1.jpg',
      action: () => navigate('/courses'),
    },
    {
      title: '直播课堂',
      description: '实时互动，与名师面对面学习',
      image: '/images/banner2.jpg',
      action: () => navigate('/live'),
    },
    {
      title: '学习社区',
      description: '与同学交流，分享学习心得',
      image: '/images/banner3.jpg',
      action: () => navigate('/community'),
    },
  ];

  const renderBanner = () => (
    <Carousel autoplay className="home-banner">
      {bannerItems.map((item, index) => (
        <div key={index} className="banner-item">
          <div className="banner-content">
            <h2>{item.title}</h2>
            <p>{item.description}</p>
            <Button type="primary" size="large" onClick={item.action}>
              立即体验
            </Button>
          </div>
          <div className="banner-image">
            <img src={item.image} alt={item.title} />
          </div>
        </div>
      ))}
    </Carousel>
  );

  const renderStats = () => (
    <Row gutter={[16, 16]} className="stats-section">
      <Col xs={12} sm={6}>
        <Card>
          <Statistic
            title="总课程数"
            value={stats.totalCourses}
            prefix={<BookOutlined />}
            valueStyle={{ color: '#1890ff' }}
          />
        </Card>
      </Col>
      <Col xs={12} sm={6}>
        <Card>
          <Statistic
            title="学员总数"
            value={stats.totalStudents}
            prefix={<UserOutlined />}
            valueStyle={{ color: '#52c41a' }}
          />
        </Card>
      </Col>
      <Col xs={12} sm={6}>
        <Card>
          <Statistic
            title="教师数量"
            value={stats.totalTeachers}
            prefix={<UserOutlined />}
            valueStyle={{ color: '#faad14' }}
          />
        </Card>
      </Col>
      <Col xs={12} sm={6}>
        <Card>
          <Statistic
            title="直播课程"
            value={stats.totalLives}
            prefix={<VideoCameraOutlined />}
            valueStyle={{ color: '#f5222d' }}
          />
        </Card>
      </Col>
    </Row>
  );

  const renderFeaturedCourses = () => (
    <Card title="推荐课程" className="featured-courses">
      <Row gutter={[16, 16]}>
        {featuredCourses.map((course) => (
          <Col xs={24} sm={12} md={8} key={course.id}>
            <Card
              hoverable
              cover={
                <div className="course-cover">
                  <img alt={course.title} src={course.cover_image} />
                  <div className="course-overlay">
                    <PlayCircleOutlined />
                  </div>
                </div>
              }
              onClick={() => navigate(`/courses/${course.id}`)}
            >
              <Card.Meta
                title={course.title}
                description={
                  <div>
                    <p className="course-description">{course.description}</p>
                    <div className="course-meta">
                      <span>
                        <EyeOutlined /> {course.view_count}
                      </span>
                      <span>
                        <StarOutlined /> {course.rating}
                      </span>
                      <span>
                        <ClockCircleOutlined /> {course.duration}
                      </span>
                    </div>
                    <div className="course-price">
                      <span className="price">¥{course.price}</span>
                      {course.original_price && (
                        <span className="original-price">¥{course.original_price}</span>
                      )}
                    </div>
                  </div>
                }
              />
            </Card>
          </Col>
        ))}
      </Row>
    </Card>
  );

  const renderLiveStreams = () => (
    <Card title="正在直播" className="live-streams">
      <List
        itemLayout="horizontal"
        dataSource={liveStreams}
        renderItem={(live) => (
          <List.Item
            actions={[
              <Button
                type="primary"
                size="small"
                onClick={() => navigate(`/live/${live.id}`)}
              >
                观看直播
              </Button>
            ]}
          >
            <List.Item.Meta
              avatar={
                <Avatar
                  src={live.teacher?.avatar}
                  icon={<UserOutlined />}
                  size="large"
                />
              }
              title={
                <div>
                  {live.title}
                  <Tag color="red" style={{ marginLeft: 8 }}>
                    直播中
                  </Tag>
                </div>
              }
              description={
                <div>
                  <p>讲师: {live.teacher?.nickname}</p>
                  <p>观看人数: {live.viewer_count}</p>
                </div>
              }
            />
          </List.Item>
        )}
      />
    </Card>
  );

  return (
    <div className="home-page">
      {renderBanner()}
      
      <div className="home-content">
        {renderStats()}
        
        <Row gutter={[24, 24]}>
          <Col xs={24} lg={16}>
            {renderFeaturedCourses()}
          </Col>
          <Col xs={24} lg={8}>
            {renderLiveStreams()}
          </Col>
        </Row>
      </div>
    </div>
  );
};

export default Home; 